<?php
class IG_View_Helper_DataTable extends ZendX_JQuery_View_Helper_UiWidget
{
    /**
     *
     * @param array $columns
     * @param array|Zend_Paginator $rows
     * @param array|string $attrs
     * @param array $options
     */
    public function dataTable(array $columns, $rows, $attrs, array $options = array())
    {
        $this->view->headScript()->appendFile('/scripts/jquery/jquery.dataTable.js')
                                 ->appendFile('/js/helper.js');
        $this->view->headLink()->appendStylesheet('/style/jquery.dataTable/css/default_table_jui.css');

        if (is_string($attrs)) {
            $attrs = array('id' => $attrs);
        } else if (!is_array($attrs)) {
            throw new IG_Exception("不支持类型'" . gettype($attrs) . "'");
        }
        if (empty($attrs['id'])) throw new IG_Exception('未设置属性 ID');

        /*
        $options['aoColumns'] = array();
        if (is_array(current($columns))) {
            $options['aoColumns'] = $columns;
        } else {
            foreach ($columns as $column) {
                $options['aoColumns'][] = array('sTitle' => $column);
            }
        }
        */
        //$options += array('aaData' => $rows);
        if ($rows instanceof Zend_Paginator) {
            $options += array(
                'iDeferLoading' => $rows->getTotalItemCount(),
                'bProcessing'   => true,
                'bServerSide'   => true,
                'bFilter'       => false,
            );

            $rows = $rows->getCurrentItems();
        }

        if (isset($options['width'])) {
            $options += array(
                'sScrollX' => "100%",
                'sScrollXInner' => $options['width'],
                'bScrollCollapse' => true,
            );
            unset($options['width']);
        }

        //jquery ui 样式
        if (!isset($attrs['class'])) {
             $attrs['class'] = array();
        }
        $attrs['class'] += array('display');

        $table = $this->view->table($columns, $rows, $attrs)->createColumns();

        //字段对应键
        $dataProp = array();
        foreach ($table->getColumnsKey() as $key => $val) {
            $dataProp[] = array(
                'mDataProp' => $key,
                'bSortable' => isset($val['sort'])
            );
        }
        $options += array("aoColumns" => $dataProp);
        /*
        $cache = Zend_Registry::get('lvan_cache');
        $key = md5(__CLASS__ . $attrs['id'] . $_SERVER['REQUEST_URI']);
        $cache->save($table->getColumnsKey(), $key);
        */
        $options = ZendX_JQuery::encodeJson($options);

        $this->jquery->addOnLoad("var list = \$('#{$attrs['id']}').dataTable("
                               . "Helper.dataTable.extendParams($options));");

        return $table;
    }
}